﻿using CWCS.Common;
using CWCS.Common.Log;
using CWCS.Core.Library.PLCManager;
using CWCS.DataAccess;
using CWCS.DataAccess.DataProvider;
using CWCS.Entity;
using CWCS.Entity.Convery;
using CWCS.Entity.SRM;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading;
using MySql.Data.MySqlClient;
using CWCS.Entity.Robot;
using CWCS.BLL.WebsocketCommon;
using SuperWebSocket;
using System.Collections.Concurrent;
using static CWCS.BLL.PhotoBLL;
using CWCS.Core.Library.SmartPLCManager;

namespace CWCS.BLL
{
    public class SmartBLL : BLLBase
    {
        private LogHelper stalog;
        private LogHelper staTimelog;
        public static Thread LEDThread;
        private static Dictionary<string, string> stationlog = new Dictionary<string, string>();
        private static Dictionary<string, int> stationDSalarm = new Dictionary<string, int>();//用于记录顶升站台的报警信息,大于设定周期进行报警
        #region Event
        public delegate void ShowLogMessage(string type, string msg);
        public event ShowLogMessage ShowLogMsg;
        #endregion
        public SmartBLL()
        {
            try
            {
                stalog = new LogHelper("Convery");
                staTimelog = new LogHelper("ConveryTime");
                smartPlc = new SmartPLC();
                smartPlc.GetTaskInfo += new PLCHelper.GetPLCTaskInfo(DoWork);//业务逻辑处理
            }
            catch (Exception ex)
            {
                stalog.Debug("SmartBLL初始化时异常", ex);
                stalog.Info(string.Format("{0}初始化时异常"), new object[] { "" });
            }
        }
        #region 输送机配置
        public DataTable GetWCS_OPCItem()
        {
            try
            {
                DataTable dt = new DataTable();
                DataSet ds = DataAccessFactory.Instance.ExecuteDataSet("select * from wcs_opcsmarteletric where areacode='" + AreaCode + "-" + LineCode + "-" + ZoneCode + "' and belong >0  order BY smarteletricid", CommandType.Text, null);
                if (ds != null && ds.Tables.Count > 0)
                    dt = ds.Tables[0];
                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 智能电表设备初始化
        /// </summary>
        /// <returns></returns>
        public bool SmartInit()
        {
            try
            {
                DataTable dt = GetWCS_OPCItem();
                smartLst = SmartConvertToList(dt);
                string error = "";
                stalog.Info("区域：{0}，智能电表初始化...", new object[] { ZoneCode });
                smartPlc.InitData(smartLst, ref error);
                stalog.Info("区域：{0}，智能电表初始化完毕!", new object[] { ZoneCode });
                for (int i = 1; i <= 3; i++)
                {
                    smartPlc.Run(i);
                }

                stalog.Info("区域：{0}，智能电表准备启动完成...", new object[] { ZoneCode });
            }
            catch (Exception ex)
            {
                stalog.Info("区域：{0}，智能电表启动时发生异常，", ex);
                //throw ex;
            }
            return true;
        }
        private List<SmartEntity> SmartConvertToList(DataTable dt)
        {
            if (dt == null || dt.Rows.Count <= 0)
                throw new Exception();
            smartLst = new List<SmartEntity>();
            foreach (DataRow dr in dt.Rows)
            {
                SmartEntity ci = new SmartEntity();
                ci.Smart_C_Info = new SmartInfo();
                ci.Key_ip = dr["smartip"].ToString();
                ci.Smart_C_Info.kep_ip = dr["smartip"].ToString();
                ci.SmartDBAddress = int.Parse(dr["smartobjects"].ToString());
                ci.Smartlength = int.Parse(dr["smartlength"].ToString());
                ci.Smartvalue = int.Parse(dr["smartvalue"].ToString());
                ci.config = dr["groupname"].ToString();
                ci.Belong = dr["belong"].ToString();
                ci.equipmentnumber = dr["equipmentnumber"].ToString();
                ci.equipmenttype = dr["groupname"].ToString();
                ci.port = int.Parse(dr["port"].ToString());
                ci.Smart_C_Info.machineid = dr["machineid"].ToString();
                ci.Smart_C_Info.ZoneCode = dr["ZoneCode"].ToString();
                ci.Smart_C_Info.zone = dr["zone"].ToString();
                ci.Smart_C_Info.equipmentnumber = dr["equipmentnumber"].ToString();
                ci.Smart_C_Info.equipmenttype = dr["groupname"].ToString();
                ci.Smart_C_Info.equipmentname = dr["equipmentname"].ToString();
                smartLst.Add(ci);
            }
            return smartLst;
        }
        /// <summary>
        /// 输送机智能电表数据业务逻辑处理
        /// </summary>
        /// <param name="si"></param>
        private void DoWork(object task)
        {
            try
            {
                SmartInfo si = task as SmartInfo;
                if (task != null)
                {
                    bool b_flag = false;
                    int result = 0;
                    string msg = string.Empty;
                    DateTime dateTime = DateTime.Now;
                    ShowSmartLog("Time", "智能电表IP:" + si.kep_ip + "开始业务处理!时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                    if (InsertSmartElectricData(si.zone, si.equipmentnumber, si.equipmenttype, si.kep_ip, si.CombinedActivePower, si.TotalPositiveActivePower, si.machineid, si.equipmentname, ref msg, ref result))
                    {
                        ShowSmartLog("WriteInfo", msg);
                        if (result == 1 || result == 2)
                            b_flag = true;
                    }
                    else
                    {
                        if (msg.Length > 0)
                        {
                            ShowSmartLog("WriteInfo", msg);
                        }
                    }
                    if (b_flag)
                    {
                        cwcs_addjk_mes_uploadenergydata(si.zone, si.machineid, "UploadEnergyData", ref msg, ref result);//添加MES能源信息上传接口
                    }
                    ShowSmartLog("Time", "智能电表IP:" + si.kep_ip + "结束业务处理!时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + "。时间差:" + (DateTime.Now - dateTime).TotalMilliseconds);
                }
            }

            catch (Exception ex)
            {
                stalog.Info("智能电表业务处理异常", ex);
            }
        }
        /// <summary>
        /// 日志显示
        /// </summary>
        /// <param name="type"></param>
        /// <param name="msg"></param>
        public void ShowSmartLog(string type, string msg)
        {
            string stationlogkey = DateTime.Now.ToString("yyyyMMddHH");  //2021092401
            if (!string.IsNullOrEmpty(msg) && msg.Length > 7)//判断长度是否大于7，否则直接记录日志（避免报异常）
            {
                if (type == "WriteInfo")
                    stationlogkey = msg;
                else
                    stationlogkey = msg;
                if (type == "WriteInfo")
                {
                    var converyMsgString = Newtonsoft.Json.JsonConvert.SerializeObject(msg);
                }
                //查看是否有该键存在，不存在则进行添加，然后发送
                if (!stationlog.ContainsKey(stationlogkey))
                {
                    stationlog.Add(stationlogkey, msg);
                    if (ShowLogMsg != null)
                    {
                        if (type == "Time")
                        {
                            staTimelog.Info(msg);
                        }
                        else
                        {
                            ShowLogMsg(type, msg);
                            stalog.Info(msg);
                        }
                    }
                }
                //如果存在，则判断是否存在相同值，若相同值，则不发送，不相同则发送，并记录
                else if (stationlog[stationlogkey] != msg)
                {
                    if (ShowLogMsg != null)
                    {
                        if (type == "Time")
                        {
                            staTimelog.Info(msg);
                        }
                        else
                        {
                            ShowLogMsg(type, msg);
                            stalog.Info(msg);
                        }
                    }
                    stationlog[stationlogkey] = msg;
                }
            }
            else
            {
                if (ShowLogMsg != null)
                {
                    ShowLogMsg(type, msg);
                    stalog.Info(msg);
                }
            }
        }
        /// <summary>
        /// 添加MES能源信息上传接口
        /// </summary>
        /// <param name="zone"></param>
        /// <param name="machineid"></param>
        /// <param name="jk_name"></param>
        /// <param name="msg"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public bool cwcs_addjk_mes_uploadenergydata(string zone, string machineid, string jk_name, ref string msg, ref int result)
        {
            msg = "";
            MySqlParameter[] parms = new MySqlParameter[]
            {
                new MySqlParameter(@"i_zonecode", MySqlDbType.VarChar, 32),
                new MySqlParameter(@"i_machineid", MySqlDbType.VarChar, 32),
                new MySqlParameter(@"i_jk_name", MySqlDbType.VarChar, 32),
                new MySqlParameter(@"o_result", MySqlDbType.Int32),
                new MySqlParameter(@"o_msg", MySqlDbType.VarChar,200)
            };
            parms[0].Direction = ParameterDirection.Input;
            parms[0].Value = zone;
            parms[1].Direction = ParameterDirection.Input;
            parms[1].Value = machineid;
            parms[2].Direction = ParameterDirection.Input;
            parms[2].Value = jk_name;
            parms[3].Direction = ParameterDirection.Output;
            parms[3].Value = 0;
            parms[4].Direction = ParameterDirection.Output;
            parms[4].Value = "";
            int i = DataAccessFactory.Instance.ExecuteNonQuery("cwcs_addjk_mes_uploadenergydata", CommandType.StoredProcedure, parms);
            if (System.String.IsNullOrEmpty(parms[3].Value.ToString()) || parms[3].Value.ToString() == "0")
            {
                result = 0;
                msg = parms[4].Value.ToString();
                return false;
            }
            else
            {
                result = int.Parse(parms[3].Value.ToString());
                msg = parms[4].Value.ToString();
                return true;
            }
        }
    }
}
#endregion